package com.luodim.dialogtest;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ImageFormat;
import android.graphics.PointF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

/**
 * Created by luodi on 2017/6/22.
 */

public class BackgroundView extends View {

    private Bitmap resultBmp;
    private Context mContext;

    public BackgroundView(Context context) {
        this(context, null);
    }

    public BackgroundView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BackgroundView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
    }

    private int getCount(float sourceWidth) {
        return (int) (Math.ceil(BaseUtils.getDeviceWidth(mContext.getApplicationContext()) / sourceWidth));
    }

    public int setSrc(int source, float ratio, boolean needSplice) {
        PointF pointF = new PointF();
        pointF.y = ratio;

        Bitmap originBmp = BaseUtils.bitmapSizeFit(mContext, source, pointF, null);
        int unitWidth = originBmp == null ? 0 : originBmp.getWidth();

        Bitmap tempBmp = needSplice ? BaseUtils.spliceSameBitmaps(mContext, source, getCount(unitWidth), false) : originBmp;
        resultBmp = BaseUtils.bitmapSizeFit(mContext, tempBmp, pointF, null);
        return unitWidth;
    }

    public void setSrc(int source, float ratio, float degree) {
        PointF pointF = new PointF();
        pointF.y = ratio;

        Bitmap tempBmp = BaseUtils.rotateBitmap(mContext, source, degree);
        resultBmp = BaseUtils.bitmapSizeFit(mContext, tempBmp, pointF, null);
    }

    public int getViewWidth() {
        if (resultBmp == null) return -1;
        return resultBmp.getWidth();
    }

    public int getViewHeight() {
        if (resultBmp == null) return -1;
        return  resultBmp.getHeight();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (resultBmp != null) {
            setMeasuredDimension(resultBmp.getWidth(), resultBmp.getHeight());
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }

    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (resultBmp != null) {
            canvas.drawBitmap(resultBmp, 0, 0, null);
        } else {
            super.onDraw(canvas);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (resultBmp != null) resultBmp.recycle();
        Log.d(/*BaseUtils.TAG*/"zzz", "view is detached");
    }
}
